package com.backstage.webSocket;

import com.backstage.pojo.Chatroom;
import com.backstage.pojo.Dialogue;
import com.backstage.service.ChatroomService;
import com.backstage.service.DialogueService;
import com.backstage.utils.CommonDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class ChatMessageHandler extends TextWebSocketHandler {

    @Autowired
    ChatroomService chatroomService;

    @Autowired
    DialogueService dialogueService;

    /**
     * 保存所有的用户session
     */
    //private static Logger logger = LoggerFactory.getLogger(SpringWebSocketHandler.class);
    private static final Map<String, Map<String, WebSocketSession>> chatroomMap = new HashMap<String, Map<String, WebSocketSession>>();  //Map来存储 Chat聊天室列表，Key用CHAT_ID存储
    //private static final Map<String, WebSocketSession> users = new HashMap<String, WebSocketSession>();  //Map来存储WebSocketSession，key用USER_ID 即在线用户列表

    //用户标识ID
    private static final String USER_ID = "SESSION_USERID";
    //区域标识
    private static final String RANGE_ID = "RANGE_ID";
    //聊天室标识
    private static final String CHAT_ID = "CHAT_ID";
    //当前用户昵称
    private static final String SESSION_USER_NAME = "SESSION_USER_NAME";   //对应监听器从的key


    public ChatMessageHandler() {
    }

//    ["聊天室ID-A - String":[
//    "用户ID-1 - String":WebSocketSession,
//    "用户ID-2 - String":WebSocketSession,
//    ]，
//    "聊天室ID-B - String":[
//    "用户ID-1 - String":WebSocketSession
//    ]]

    /**
     * 连接成功时候，会触发页面上onopen方法
     */
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        System.out.println("成功建立websocket连接!");
        //System.out.println(session);

        String userId = session.getAttributes().get(USER_ID).toString();
        String chatId = session.getAttributes().get(CHAT_ID).toString();

        Map<String, WebSocketSession> stringWebSocketSessionMap = chatroomMap.get(chatId); //这是个聊天室的map,key是聊天室id,value(也是一个map)是在线用户信息
        if (stringWebSocketSessionMap == null) {
            stringWebSocketSessionMap = new HashMap<String, WebSocketSession>(); //聊天室内的用户列表容器
            stringWebSocketSessionMap.put(userId, session);
            System.out.println(chatId+"聊天室‘在线人数’:" + stringWebSocketSessionMap.size());
            chatroomMap.put(chatId, stringWebSocketSessionMap);
        } else {
            stringWebSocketSessionMap.put(userId, session);
            System.out.println(chatId+"聊天室‘在线人数’:" + stringWebSocketSessionMap.size());
        }
        System.out.println("当前‘聊天室’数量:" + chatroomMap.size());

        //准备更新当前“聊天室”在线人数，操作数据库
        Chatroom newChatroom = new Chatroom();
        newChatroom.setId(Integer.parseInt(chatId)) ;
        newChatroom.setOnlineusers(stringWebSocketSessionMap.size());
        chatroomService.selectChatroomUpdate(newChatroom);


        //这块会实现自己业务，比如，当用户登录后，会把离线消息推送给用户
        //TextMessage returnMessage = new TextMessage("成功建立socket连接，你将收到的离线");
        //session.sendMessage(returnMessage);
    }

    /**
     * 关闭连接时触发
     */
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        //logger.debug("关闭websocket连接");
        String userId = session.getAttributes().get(USER_ID).toString();
        String chatId = session.getAttributes().get(CHAT_ID).toString();
        int chatSize = 0;
        for(Map.Entry<String, Map<String, WebSocketSession>> entry : chatroomMap.entrySet()){
            if(chatId.equals(entry.getKey())){
                System.out.println(chatId+"聊天室-用户" + userId + "已退出-关闭连接！");
                entry.getValue().remove(userId);
                System.out.println(chatId+"聊天室剩余在线用户" + entry.getValue().size() +"-关闭连接");
                chatSize = entry.getValue().size();
                break;
            }
        }
        //准备更新当前“聊天室”在线人数，操作数据库
        Chatroom newChatroom = new Chatroom();
        newChatroom.setId(Integer.parseInt(chatId)) ;
        newChatroom.setOnlineusers(chatSize);
        chatroomService.selectChatroomUpdate(newChatroom);
    }

    /**
     * js调用websocket.send时候，会调用该方法
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        super.handleTextMessage(session, message);

        /**
         * 收到消息，自定义处理机制，实现业务
         */
        System.out.println("服务器收到消息：" + message);

        if (message.getPayload().startsWith("#anyone#")) { //单发某人

            //sendMessageToUser(session.getAttributes().get(USER_ID).toString(), new TextMessage("服务器单发：" + message.getPayload()));

        } else if (message.getPayload().startsWith("#everyone#")) {
            //准备记录发送者的信息，操作数据库
            String userName = session.getAttributes().get(SESSION_USER_NAME).toString();
            String userId = session.getAttributes().get(USER_ID).toString();
            String rangeId = session.getAttributes().get(RANGE_ID).toString();
            String chatId = session.getAttributes().get(CHAT_ID).toString();
            int chatSize = 0;
            for(Map.Entry<String, Map<String, WebSocketSession>> entry : chatroomMap.entrySet()){
                if(chatId.equals(entry.getKey())){
                    chatSize = entry.getValue().size();
                    break;
                }
            }
            String sendContent = message.getPayload().substring(10);
            String sendContentA = sendContent +"#"+chatId + userName +"#"+chatId + chatSize;
            System.out.println("发送内容："+sendContent);
            System.out.println("发送内容+userName："+sendContentA);
            //写入数据库
            Dialogue newDialogue = new Dialogue();
            newDialogue.setChatroomid(Integer.parseInt(chatId));
            newDialogue.setScopeid(Integer.parseInt(rangeId));
            newDialogue.setSendid(Integer.parseInt(userId));
            newDialogue.setSendnickname(userName);
            newDialogue.setSendcontent(sendContent);
            newDialogue.setSendtime(CommonDate.newData());
            dialogueService.selectDialogueInsert(newDialogue);
            //去发送
            sendMessageToUsers(chatId, userId, new TextMessage(sendContentA));

        } else {

        }

    }

    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        //logger.debug("传输出现异常，关闭websocket连接... ");
//        String userId = session.getAttributes().get(CHAT_ID).toString();
//        users.remove(userId);
        String userId = session.getAttributes().get(USER_ID).toString();
        String chatId = session.getAttributes().get(CHAT_ID).toString();
        for(Map.Entry<String, Map<String, WebSocketSession>> entry : chatroomMap.entrySet()){
            if(chatId.equals(entry.getKey())){
                System.out.println(chatId+"聊天室-用户" + userId + "已退出！");
                entry.getValue().remove(userId);
                System.out.println(chatId+"聊天室剩余在线用户" + entry.getValue().size());
                break;
            }
        }
    }

    //是否支持分包
    public boolean supportsPartialMessages() {
        return false;
    }


    /**
     * 给某个用户发送消息
     *
     * @param userId
     * @param message
     */
//    public void sendMessageToUser(String userId, TextMessage message) {
//        for (String id : users.keySet()) {
//            if (id.equals(userId)) {
//                try {
//                    if (users.get(id).isOpen()) {
//                        users.get(id).sendMessage(message);
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                break;
//            }
//        }
//    }

    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(String chat_id, String user_id, TextMessage message) {
//        for (String userId : users.keySet()) {
//            try {
//                if (users.get(userId).isOpen()) {
//                    users.get(userId).sendMessage(message);
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        for(Map.Entry<String, Map<String, WebSocketSession>> entry : chatroomMap.entrySet()){
            if(chat_id.equals(entry.getKey())){
                for (String userId : entry.getValue().keySet()) {
                    if(!userId.equals(user_id)){
                        try {
                            if (entry.getValue().get(userId).isOpen()) {
                                entry.getValue().get(userId).sendMessage(message);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
            }
        }

    }

}
